package com.imooc.service;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.imooc.bean.Account;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Author 14048
 * @Date 2022/1/14 17:43
 */
@Service
@Slf4j
public class JwtService {

    private static final Long TOKEN_EXP=10000000L;
    //加密密钥
    private static final String KEY="KEY";
    //发行者
    private static final String ISSUER="ISSUER";
    private static final String USER_NAME="username";

    public String token(Account account) {
        Date date = new Date();
        Algorithm algorithm = Algorithm.HMAC256(KEY);
        String token= JWT.create().withIssuer(ISSUER).withIssuedAt(date)
                .withExpiresAt(new Date(date.getTime()+TOKEN_EXP))
                .withClaim(USER_NAME,account.getUserName()).sign(algorithm);
        log.info("JWT user:{}",token);
        return token;
    }

    public Boolean verify(String token,String username){
        try {
            Algorithm algorithm = Algorithm.HMAC256(KEY);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(ISSUER)
                    .withClaim(USER_NAME,username)
                    .build();
            //验证失败会抛出错误！
            verifier.verify(token);
            return true;
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return  false;
        }

    }


}
